﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OBUActivation
{
    class HexConverter
    {
        public static string HexToStr(byte[] hex)
        {
            string tmpStr = "";
            for (int i = 0; i < hex.Length; i++)
            {
                tmpStr += hex[i].ToString("X2");
            }
            return tmpStr;
        }
        public static string HexToStr(byte[] hex, int len)
        {
            string tmpStr = "";
            int dataLen = len < hex.Length ? len : hex.Length;
            for (int i = 0; i < dataLen; i++)
            {
                tmpStr += hex[i].ToString("X2");
            }
            return tmpStr;
        }
        public static byte[] StrToHex(string str)
        {
            int len = str.Length / 2;
            byte[] hex = new byte[len];
            for (int i = 0; i < len; i++)
            {
                hex[i] = Convert.ToByte("0x" + str.Substring(2 * i, 2), 16);
            }
            return hex;
        }

        /// <summary>
        /// 将 DateTime 类型转换为 long 类型
        /// </summary>
        /// <param name="dt">时间</param>
        /// <returns>长整型值</returns>
        public static long DateTimeToLong(DateTime dt)
        {

            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0));
            TimeSpan toNow = dt.Subtract(dtStart);
            long timeStamp = toNow.Ticks / 10000;
            return timeStamp;
        }

        /// <summary>
        /// 将长整类型转换为DateTime类型
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static DateTime LongToDateTime(long time)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 0, 0, 0));
            long lTime = long.Parse(time + "0000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }
    }
}
